import * as types from '../../constants/ActionTypes';
import api from '../../api'
import {showMsg} from '../other'

export function fetchUserLogin(userInfo) {
    return (dispatch, getState)=> {
        return api.userLoginAPI(userInfo)
            .then(response => ({json: response.data}))
            .then(json => {//成功message为token，失败则为失败消息
                if (json.json.Code === 10) {
                    dispatch(fetchUserProfile(json.Message));
                } else {
                    dispatch(showMsg(json.Message))
                // dispatch({type: types.USER_LOGIN_FAILURE, message: message})
                }
            })
            .catch(err => {
                return dispatch(showMsg(err || '登录失败'))
                // return dispatch({type: types.USER_LOGIN_FAILURE, message: err.message})
            })
    }
}

export function fetchUserProfile(token) {
    return dispatch => {
        return api.getUserProfileAPI(token)
            .then(response => ({json: response.data}))
            .then(json => {
                console.log('2' + json)
                if (json.Code === 10) {
                    return dispatch({type: types.USER_LOGIN_SUCCESS, userId: json.Data.USER_ID, token: json.Message})
                } else {
                    dispatch(showMsg(json.Message))
                }
            })
            .then(err => {
                return dispatch(showMsg(err || '登录失败'))
            })
    }
}

export function fetchUserRegister(userInfo) {
    return (dispatch, getState) => {

    }
}